package kz.kstu.scantest.business.server.impl;

import kz.kstu.scantest.business.common.exception.LoginFailedException;
import kz.kstu.scantest.business.entity.CommonEntityConstant;
import kz.kstu.scantest.business.entity.security.Account;
import kz.kstu.scantest.business.server.api.AccountService;

import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.security.auth.login.LoginException;


/**
 * @author Filipp_Stankevich
 *         created: 08.09.11 15:42
 */
public class AccountServiceImpl extends AbstractService implements AccountService {

    @Override
    public Account login(String login, String password) throws LoginException {
        Query query = getEntityManager().createNamedQuery(CommonEntityConstant.FIND_ACCOUNT_BY_LOGIN_AND_PASSWORD);
        query.setParameter("login", login);
        query.setParameter("password", password);
        Account account;
        try {
            account = (Account) query.getSingleResult();
        } catch (NoResultException e) {
            throw new LoginFailedException();
        }
        return account;
    }

    @Override
    public void changePassword(Long accountId, String newPassword) {
        Query query = getEntityManager().createNamedQuery(CommonEntityConstant.UPDATE_PASSWORD_BY_ACCOUNT_ID);
        query.setParameter("id", accountId);
        query.setParameter("password", newPassword);
        query.executeUpdate();
    }
}
